package com.member.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.member.common.annotation.Log;
import com.member.common.constant.SystemConst;
import com.member.common.core.controller.BaseController;
import com.member.common.core.domain.AjaxResult;
import com.member.common.core.domain.entity.SysDictData;
import com.member.common.core.domain.model.LoginUser;
import com.member.common.core.page.TableDataInfo;
import com.member.common.enums.BusinessType;
import com.member.common.enums.EnableStatusEnum;
import com.member.common.enums.OrderDeleteEnum;
import com.member.common.utils.StringUtils;
import com.member.common.utils.poi.ExcelUtil;
import com.member.shop.domain.*;
import com.member.shop.service.*;
import com.member.system.service.ISysDictDataService;
import com.member.system.service.ISysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 数据字典信息
 *
 * @author wangxin
 */
@RestController
@RequestMapping("/system/dict/data")
public class SysDictDataController extends BaseController {
    @Resource
    private ISysDictDataService dictDataService;

    @Resource
    private ISysDictTypeService dictTypeService;

    @PreAuthorize("@ss.hasPermi('system:dict:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysDictData dictData) {
        startPage();
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        return getDataTable(list);
    }

    @Log(title = "字典数据", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:dict:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysDictData dictData) {
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        ExcelUtil<SysDictData> util = new ExcelUtil<SysDictData>(SysDictData.class);
        util.exportExcel(response, list, "字典数据");
    }

    /**
     * 查询字典数据详细
     */
    @PreAuthorize("@ss.hasPermi('system:dict:query')")
    @GetMapping(value = "/{dictCode}")
    public AjaxResult getInfo(@PathVariable Long dictCode) {
        return success(dictDataService.selectDictDataById(dictCode));
    }

    @Resource
    private ISysBizShopCategoryService sysBizShopCategoryService;

    @Resource
    private ISysBizTenantService sysBizTenantService;

    @Resource
    private ISysBizTenantAreaService sysBizTenantAreaService;
    @Resource
    private ISysBizMarketPageCategoryService marketPageCategoryService;

    @Resource
    private ISysBizMarketPageService marketPageService;
    @Resource
    private ISysBizRecommendCategoryService recommendCategoryService;

    @Autowired
    private ISysBizCouponService couponService;
    @Autowired
    private ISysBizRankListService rankListService;

    /**
     * 根据字典类型查询字典数据信息
     */
    @GetMapping(value = "/type/{dictType}")
    public AjaxResult dictType(@PathVariable String dictType) {

        LoginUser loginUser = getLoginUser();
        Long tenantId = loginUser.getTenantId();


        List<SysDictData> data = Lists.newArrayList();
        if (SystemConst.BIZ_GOODS_CATEGORY.equals(dictType)) {

            LambdaQueryWrapper<SysBizShopCategory> queryWrapper = new LambdaQueryWrapper<SysBizShopCategory>();
            queryWrapper.eq(SysBizShopCategory::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
            queryWrapper.ne(SysBizShopCategory::getParentId, OrderDeleteEnum.NOT_DELETE.getKey());
            if (tenantId != null && tenantId > 0) {
                queryWrapper.eq(SysBizShopCategory::getTenantId, tenantId);
            }

            queryWrapper.orderByDesc(SysBizShopCategory::getOrderNum);
            List<SysBizShopCategory> lists = sysBizShopCategoryService.selectSysBizShopCategoryList(queryWrapper);


            for (SysBizShopCategory list : lists) {

                Long id = list.getId();
                String name = list.getCategoryName();

                SysDictData dictData = new SysDictData();
                dictData.setDictLabel(name);
                dictData.setDictValue(String.valueOf(id));

                dictData.setListClass("");
                dictData.setDictCode(id);
                dictData.setDictSort(list.getOrderNum());
                dictData.setDictType(dictType);
                data.add(dictData);
            }
            //通用券
        } else if (SystemConst.BIZ_COUPON_LIST.equals(dictType)) {

            LambdaQueryWrapper<SysBizCoupon> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysBizCoupon::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
            if (tenantId != null && tenantId > 0) {
                queryWrapper.eq(SysBizCoupon::getTenantId, tenantId);
            }
            queryWrapper.eq(SysBizCoupon::getScopeUse, 1);
            queryWrapper.orderByDesc(SysBizCoupon::getOrderNum);
            List<SysBizCoupon> lists = couponService.selectSysBizCouponList(queryWrapper);


            for (SysBizCoupon list : lists) {

                Long id = list.getId();
                String name = list.getName();

                SysDictData dictData = new SysDictData();
                dictData.setDictLabel(name);
                dictData.setDictValue(String.valueOf(id));

                dictData.setListClass("");
                dictData.setDictCode(id);
                dictData.setDictSort(list.getOrderNum());
                dictData.setDictType(dictType);
                data.add(dictData);
            }
        } else if (SystemConst.BIZ_RECOMMEND_CATEGORY.equals(dictType)) {

            LambdaQueryWrapper<SysBizRecommendCategory> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysBizRecommendCategory::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
            if (tenantId != null && tenantId > 0) {
                queryWrapper.eq(SysBizRecommendCategory::getTenantId, tenantId);
            }
            queryWrapper.orderByDesc(SysBizRecommendCategory::getOrderNum);
            List<SysBizRecommendCategory> lists = recommendCategoryService.list(queryWrapper);


            for (SysBizRecommendCategory list : lists) {

                Long id = list.getId();
                String name = list.getName();

                SysDictData dictData = new SysDictData();
                dictData.setDictLabel(name);
                dictData.setDictValue(String.valueOf(id));

                dictData.setListClass("");
                dictData.setDictCode(id);
                dictData.setDictSort(list.getOrderNum());
                dictData.setDictType(dictType);
                data.add(dictData);
            }
        } else if (SystemConst.BIZ_MARKET_PAGE.equals(dictType)) {

            LambdaQueryWrapper<SysBizMarketPage> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysBizMarketPage::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
            if (tenantId != null && tenantId > 0) {
                queryWrapper.eq(SysBizMarketPage::getTenantId, tenantId);
            }
            queryWrapper.orderByDesc(SysBizMarketPage::getOrderNum);
            List<SysBizMarketPage> lists = marketPageService.list(queryWrapper);


            for (SysBizMarketPage list : lists) {

                Long id = list.getId();
                String name = "";

                SysDictData dictData = new SysDictData();
                dictData.setDictLabel(name);
                dictData.setDictValue(String.valueOf(id));

                dictData.setListClass("");
                dictData.setDictCode(id);
                dictData.setDictSort(list.getOrderNum());
                dictData.setDictType(dictType);
                data.add(dictData);
            }
        } else if (SystemConst.BIZ_MARKET_PAGE_CATEGORY.equals(dictType)) {

            LambdaQueryWrapper<SysBizMarketPageCategory> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysBizMarketPageCategory::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
            if (tenantId != null && tenantId > 0) {
                queryWrapper.eq(SysBizMarketPageCategory::getTenantId, tenantId);
            }
            queryWrapper.orderByDesc(SysBizMarketPageCategory::getOrderNum);
            List<SysBizMarketPageCategory> lists = marketPageCategoryService.list(queryWrapper);


            for (SysBizMarketPageCategory list : lists) {

                Long id = list.getId();
                String name = "";

                SysDictData dictData = new SysDictData();
                dictData.setDictLabel(name);
                dictData.setDictValue(String.valueOf(id));

                dictData.setListClass("");
                dictData.setDictCode(id);
                dictData.setDictSort(list.getOrderNum());
                dictData.setDictType(dictType);
                data.add(dictData);
            }
        } else if (SystemConst.BIZ_TENANT.equals(dictType)) {

            LambdaQueryWrapper<SysBizTenant> queryWrapper = new LambdaQueryWrapper<>();

            if (tenantId != null && tenantId > 0) {
                queryWrapper.eq(SysBizTenant::getId, tenantId);
            } else {

                SysDictData dictData = new SysDictData();
                dictData.setDictLabel("全部");
                dictData.setDictValue(String.valueOf(0));

                dictData.setListClass("");
                dictData.setDictCode(0L);
                dictData.setDictSort(0L);
                dictData.setDictType(dictType);
                data.add(dictData);
            }
            queryWrapper.orderByDesc(SysBizTenant::getIsDefault);
            queryWrapper.orderByDesc(SysBizTenant::getOrderNum);
            List<SysBizTenant> lists = sysBizTenantService.selectSysBizTenantList(queryWrapper);


            for (SysBizTenant list : lists) {

                Long id = list.getId();
                String name = list.getName();

                SysDictData dictData = new SysDictData();
                dictData.setDictLabel(name);
                dictData.setDictValue(String.valueOf(id));

                dictData.setListClass("");
                dictData.setDictCode(id);
                dictData.setDictSort(list.getOrderNum());
                dictData.setDictType(dictType);
                data.add(dictData);
            }
        } else if (SystemConst.BIZ_TENANT_EDIT.equals(dictType)) {

            LambdaQueryWrapper<SysBizTenant> queryWrapper = new LambdaQueryWrapper<>();

            if (tenantId != null && tenantId > 0) {
                queryWrapper.eq(SysBizTenant::getId, tenantId);
            }
            queryWrapper.orderByDesc(SysBizTenant::getIsDefault);
            queryWrapper.orderByDesc(SysBizTenant::getOrderNum);
            List<SysBizTenant> lists = sysBizTenantService.selectSysBizTenantList(queryWrapper);


            for (SysBizTenant list : lists) {

                Long id = list.getId();
                String name = list.getName();

                SysDictData dictData = new SysDictData();
                dictData.setDictLabel(name);
                dictData.setDictValue(String.valueOf(id));

                dictData.setListClass("");
                dictData.setDictCode(id);
                dictData.setDictSort(list.getOrderNum());
                dictData.setDictType(dictType);
                data.add(dictData);
            }
        } else if (SystemConst.BIZ_TENANT_AREA.equals(dictType)) {

            //LambdaQueryWrapper<SysBizTenantArea> queryWrapper = new LambdaQueryWrapper<>();
            //queryWrapper.eq(SysBizTenantArea::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
            //
            //queryWrapper.orderByDesc(SysBizTenantArea::getOrderNum);
            //List<SysBizTenantArea> lists = sysBizTenantAreaService.selectSysBizTenantAreaList(queryWrapper);
            //
            //
            //for (SysBizTenantArea list : lists) {
            //
            //    Long id = list.getId();
            //    String name = list.get();
            //
            //    SysDictData dictData = new SysDictData();
            //    dictData.setDictLabel(name);
            //    dictData.setDictValue(String.valueOf(id));
            //
            //    dictData.setListClass("");
            //    dictData.setDictCode(id);
            //    dictData.setDictSort(list.getOrderNum());
            //    dictData.setDictType(dictType);
            //    data.add(dictData);
            //}
        } else {
            data = dictTypeService.selectDictDataByType(dictType);
        }
        return success(data);
    }

    private static SysDictData getSysDictData(Long id, String name, String dictType) {
        SysDictData dictData = new SysDictData();
        dictData.setDictLabel(name);
        dictData.setDictValue(String.valueOf(id));
        dictData.setListClass(StringUtils.EMPTY);
        dictData.setDictCode(id);
        dictData.setDictSort(id);
        dictData.setListClass("default");
        dictData.setDictType(dictType);
        return dictData;
    }

    /**
     * 新增字典类型
     */
    @PreAuthorize("@ss.hasPermi('system:dict:add')")
    @Log(title = "字典数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDictData dict) {
        dict.setCreateBy(getUsername());
        return toAjax(dictDataService.insertDictData(dict));
    }

    /**
     * 修改保存字典类型
     */
    @PreAuthorize("@ss.hasPermi('system:dict:edit')")
    @Log(title = "字典数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDictData dict) {
        dict.setUpdateBy(getUsername());
        return toAjax(dictDataService.updateDictData(dict));
    }

    /**
     * 删除字典类型
     */
    @PreAuthorize("@ss.hasPermi('system:dict:remove')")
    @Log(title = "字典类型", businessType = BusinessType.DELETE)
    @DeleteMapping("/{dictCodes}")
    public AjaxResult remove(@PathVariable Long[] dictCodes) {
        dictDataService.deleteDictDataByIds(dictCodes);
        return success();
    }
}
